﻿using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YJKRevitBase.WinForm;
using YJKRevitView;

namespace YJKFamilyFindder.YJKFamilyFindder
{
	[Transaction(TransactionMode.Manual)]
	[Regeneration(RegenerationOption.Manual)]
	public class CmdSearchingComponents : IExternalCommand
	{
		[DllImport("User32.dll")]
		private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

		public Result Execute(ExternalCommandData cmdData, ref string msg, ElementSet elems)
		{
			Result result;
			try
			{
				if (cmdData == null)
				{
					throw new System.ArgumentNullException("commandData");
				}
				CmdViewType types = (CmdViewType)127;
				if (SwitchView.SetUsableView(types, cmdData) != Autodesk.Revit.UI.Result.Succeeded)
				{
					result = Autodesk.Revit.UI.Result.Failed;
				}
				else
				{
					IntPtr value = CmdSearchingComponents.FindWindow(null, "构件检索");
					if (IntPtr.Zero != value)
					{
						result = Autodesk.Revit.UI.Result.Cancelled;
					}
					else
					{
						if (CmdSearchingComponents._hWndRevit == null)
						{
							CmdSearchingComponents._hWndRevit = new WindowHandle(Process.GetCurrentProcess().MainWindowHandle);
						}
						new SearchingComponentsForm(cmdData).Show(CmdSearchingComponents._hWndRevit);
						result = Autodesk.Revit.UI.Result.Succeeded;
					}
				}
			}
			catch (Exception ex)
			{
				msg = ex.Message;
				result = Autodesk.Revit.UI.Result.Failed;
			}
			return result;
		}

		public static WindowHandle _hWndRevit;
	}
}
